package com.pms.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.controller.BaseController;
import com.pms.entity.EntranceDoor;
import com.pms.entity.EstateAgency;
import com.pms.entity.EstateDoorLock;
import com.pms.entity.UnitBuilding;
import com.pms.exception.R;
import com.pms.service.IEntranceDoorService;
import com.pms.service.IEstateAgencyService;
import com.pms.service.IEstateDoorLockService;
import com.pms.service.IUnitBuildingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ASUS_B
 * @since 2017-10-24
 */
@RestController
@RequestMapping("/entranceDoorBase")
@Api(value="门信息管理",description = "门信息管理界面接口")
public class EntranceDoorController extends BaseController {
    @Autowired
    private IUnitBuildingService unitBuildingService;
    @Autowired
    private IEstateAgencyService estateAgencyService;
    @Autowired
    private IEntranceDoorService entranceDoorService;
    @Autowired
    private IEstateDoorLockService estateDoorLockService;
    @ApiOperation(value = "添加门")
    @RequestMapping(value = "/addDoor", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "doorName", value = "门名称", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "conmunityId", value = "社区id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "doorType", value = "门类型(1-大门，2单元门，3车库门)", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "unitId", value = "单元id", required = false, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "doorRemarks", value = "备注信息", required = false, dataType = "String", paramType = "form"),
    })
    public R addDoor(String doorName, Integer doorType, Long conmunityId, Long unitId, String doorRemarks) {
        parameterIsBlank(doorName, "请填写门名称");
        parameterIsNull(conmunityId, "社区id不能为空");
        if (null == doorType || doorType > 3 || doorType < 1) {
            return R.error(400, "门类型出错");
        }//默认App显示
        if (StringUtils.isBlank(doorRemarks)) {
            doorRemarks = "";
        }
        if (doorRemarks.length() > 199) {
            return R.error(400, "描述信息内容过长");
        }
        if (doorName.length() > 40) {
            return R.error(400, "门名称内容过长");
        }
        EstateAgency community = estateAgencyService.selectById(conmunityId);
        if (null == community) {
            return R.error(400, "没有该社区信息");
        }
        if (null == community.getAgencyType() || community.getAgencyType() != 2) {
            return R.error(400, "没有该社区信息");
        }
        int countDoorName = entranceDoorService.selectCount(new EntityWrapper<EntranceDoor>().eq("community_id", conmunityId).eq("door_name", doorName));
        if (countDoorName > 0) {
            return R.error(400, "为避免重复，请修改门名称");
        }
        UnitBuilding unit = null;
        EntranceDoor door = new EntranceDoor();
        if (doorType != 1) {
            if (null == unitId) {
                return R.error(400, "请选择门对应的单元");
            }
            unit = unitBuildingService.selectById(unitId);
            if (null == unit) {
                return R.error(400, "没有该单元信息");
            }
        }

        door.setCommunityId(community.getAgencyId()).setAgencyId(community.getParentId())
                .setDoorRemarks(doorRemarks).setDoorName(doorName.trim()).setDoorType(doorType).setCommunityNum(community.getCommunityNum());
        if (doorType == 1) {
            door.setUnitNum(0);
            door.setUnitName("");
        }
        if (doorType != 1) {
            door.setUnitId(unit.getUnitId());
            door.setUnitNum(unit.getUnitNum());
            door.setUnitName(unit.getUnitName());
        }
        door.setIsHaveLock(2);
        entranceDoorService.insert(door);
        return R.ok();
    }

    @ApiOperation(value = "修改门")
    @RequestMapping(value = "/editDoor", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "doorName", value = "门名称", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "doorId", value = "门id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "doorRemarks", value = "备注信息", required = false, dataType = "String", paramType = "form"),
    })
    public R editDoor(String doorName, Long doorId, String doorRemarks) {
        parameterIsNull(doorId, "门id不能为空");
        if (StringUtils.isBlank(doorRemarks)) {
            doorRemarks = "";
        }
        if (doorRemarks.length() > 199) {
            return R.error(400, "描述信息内容过长");
        }
        EntranceDoor oldDoor = entranceDoorService.selectById(doorId);
        if (null == oldDoor) {
            return R.error(400, "没有该门信息");
        }
        boolean editTag = false;
        boolean editDoorNameTag = false;
        if (StringUtils.isNotBlank(doorName)) {
            doorName = doorName.trim();
            if (!doorName.equals(oldDoor.getDoorName())) {
                if (doorName.length() > 40) {
                    return R.error(400, "门名称内容过长");
                }
                int countDoorName = entranceDoorService.selectCount(new EntityWrapper<EntranceDoor>().eq("community_id", oldDoor.getCommunityId()).eq("door_name", doorName));
                if (countDoorName > 0) {
                    return R.error(400, "为避免重复，请修改门名称");
                }
                editTag = true;
                editDoorNameTag = true;
                oldDoor.setDoorName(doorName);
            }
        }
        if (!doorRemarks.equals(oldDoor.getDoorRemarks())) {
            editTag = true;
            oldDoor.setDoorRemarks(doorRemarks);
        }
        if (editTag) {
            entranceDoorService.updateById(oldDoor);
            if(editDoorNameTag==true){
                //修改关联表 门名称
                entranceDoorService.updateJoinTableDoorName(oldDoor.getDoorId());
            }
        }
        return R.ok();
    }

    @ApiOperation(value = "查询门信息")
    @RequestMapping(value = "/readInfo",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="doorId",value="门id",required = true,dataType = "long",paramType="form"),
    })
    public R readInfo(Long doorId) {
        parameterIsNull(doorId,"门id不能为空");
        EntranceDoor oldDoor = entranceDoorService.selectById(doorId);
        parameterIsNull(oldDoor,"未查询到门信息");
        return R.ok().put("data",oldDoor).putDescription(EntranceDoor.class);
    }

    @ApiOperation(value = "分页查询门")
    @RequestMapping(value = "/readPage",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="pageSize",value="请求条数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="pageNum",value="请求页数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="conmunityId",value="社区id",required = false,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="agencyId",value="物业机构id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="unitId",value="单元id",required = false,dataType = "long",paramType="form"),
            @ApiImplicitParam(name ="doorType", value = "门类型(1-大门，2单元门，3车库门)", required = false, dataType = "int", paramType = "form"),
    })
    public R readPage(Integer pageSize,Integer pageNum,Long conmunityId,Integer doorType,Long agencyId,Long unitId) {
        parameterIsNull(agencyId,"物业机构id不能为空");
        if(null==pageNum||pageNum<1){pageNum=1;}
        if(null==pageSize||pageSize<1){pageSize=10;}
        Page<EntranceDoor> page = new Page<EntranceDoor>(pageNum,pageSize);
        Wrapper<EntranceDoor> wrapper=  new EntityWrapper<EntranceDoor>();
        if(null!=agencyId){
            wrapper.eq("agency_id",agencyId);
        }
        if(null!=conmunityId){
            wrapper.eq("community_id",conmunityId);
        }
        if(null!=doorType) {
            if(doorType<1||doorType>3){
                doorType = null;
            }
        }
        if(unitId!=null){
            if(doorType!=null){
                wrapper.eq("door_type",doorType);
                if(doorType!=1){
                    wrapper.eq("unit_id",unitId);
                }
            }
            if(doorType==null){
                wrapper.and("door_type = {0} or unit_id = {1}",1,unitId);
            }
        }
        if(unitId==null){
            if(doorType!=null){
                wrapper.eq("door_type",doorType);
            }
        }
        Page<EntranceDoor> returnPage = entranceDoorService.selectPage(page,wrapper);
        return R.ok().put("data",returnPage).putMpPageDescription().putDescription(EntranceDoor.class);
    }

    @ApiOperation(value = "查询门集合")
    @RequestMapping(value = "/readList",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="conmunityId",value="社区id",required = false,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="agencyId",value="物业机构id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="unitId",value="单元id",required = false,dataType = "long",paramType="form"),
            @ApiImplicitParam(name ="doorType", value = "门类型(1-大门，2单元门，3车库门)", required = false, dataType = "int", paramType = "form"),
    })
    public R readList(Long conmunityId,Integer doorType,Long agencyId,Long unitId) {
        parameterIsNull(agencyId,"物业机构id不能为空");
        Wrapper<EntranceDoor> wrapper=  new EntityWrapper<EntranceDoor>();
        if(null!=agencyId){
            wrapper.eq("agency_id",agencyId);
        }
        if(null!=conmunityId){
            wrapper.eq("community_id",conmunityId);
        }
        if(null!=doorType) {
            if(doorType<1||doorType>3){
                doorType = null;
            }
        }
        if(unitId!=null){
            if(doorType!=null){
                wrapper.eq("door_type",doorType);
                if(doorType!=1){
                    wrapper.eq("unit_id",unitId);
                }
            }
            if(doorType==null){
                wrapper.and("door_type = {0} or unit_id = {1}",1,unitId);
            }
        }
        if(unitId==null){
            if(doorType!=null){
                wrapper.eq("door_type",doorType);
            }
        }
        List<EntranceDoor> returnPage = entranceDoorService.selectList(wrapper);
        if(returnPage==null){ returnPage = new ArrayList<EntranceDoor>();}
        return R.ok().put("data",returnPage).putDescription(EntranceDoor.class);
    }

    @ApiOperation(value = "删除门信息")
    @RequestMapping(value = "/delDoor",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="doorId",value="门id",required = true,dataType = "long",paramType="form"),
    })
    public R delDoor(Long doorId) {
        parameterIsNull(doorId,"门id不能为空");
        EntranceDoor oldDoor = entranceDoorService.selectById(doorId);
        if(oldDoor== null){
            return R.error(400, "未查询到该门信息");
        }
        /**
         * 验证是否有设备
         */
        if(oldDoor.getIsHaveLock()!=null&&oldDoor.getIsHaveLock()==1){
            return R.error(400, "无法删除，请先解除门锁绑定");
        }
        entranceDoorService.deleteById(doorId);
        return R.ok();
    }
}
